package com.chonor.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.chonor.mall.dao.*;
import com.chonor.mall.dto.ProductParam;
import com.chonor.mall.dto.ProductQueryParam;
import com.chonor.mall.dto.ProductResult;
import com.chonor.mall.mapper.*;
import com.chonor.mall.model.*;
import com.chonor.mall.service.BrandService;
import com.chonor.mall.service.ProductCategoryService;
import com.chonor.mall.service.ProductService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private MemberPriceDao memberPriceDao;

    @Autowired
    private MemberPriceMapper memberPriceMapper;

    @Autowired
    private ProductLadderDao productLadderDao;

    @Autowired
    private ProductLadderMapper productLadderMapper;

    @Autowired
    private ProductFullReductionDao productFullReductionDao;

    @Autowired
    private ProductFullReductionMapper productFullReductionMapper;

    @Autowired
    private SkuStockDao skuStockDao;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private ProductAttributeValueDao productAttributeValueDao;

    @Autowired
    private ProductAttributeValueMapper productAttributeValueMapper;

//    @Autowired
//    private CmsSubjectProductRelationDao subjectProductRelationDao;
//    @Autowired
//    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
//    @Autowired
//    private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;
//    @Autowired
//    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private ProductDao productDao;
//    @Autowired
//    private ProductVertifyRecordDao productVertifyRecordDao;

    @Override
    public int create(ProductParam productParam) {
        //创建商品
        Product product = productParam;
        product.setId(null);
        product.setIsdelete(0);
        //商品编码
        String code = RandomUtil.randomNumbers(6);
        product.setCode("PR"+code);
        product.setSale(0);
        product.setPromotionType(0);

        //冗余品牌，商品分类
        Brand brand = brandService.getBrand(productParam.getBrandId());
        if(!Objects.isNull(brand)){
            product.setBrandName(brand.getName());
        }

        ProductCategory productCategory = productCategoryService.getItem(productParam.getProductCategoryId());
        if(!Objects.isNull(productCategory)){
            product.setProductCategoryName(productCategory.getName());
        }

        int count = productMapper.insert(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
//        Long productId = product.getId();
//        //会员价格
//        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId);
//        //阶梯价格
//        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), productId);
//        //满减价格
//        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
//        //处理sku的编码
//        handleSkuStockCode(productParam.getSkuStockList(),productId);
//        //添加sku库存信息
//        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId);
//        //添加商品参数,添加自定义商品规格
//        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId);
//        count = 1;
        return count;
    }

    private void handleSkuStockCode(List<SkuStock> skuStockList, Long productId) {
        if(CollectionUtils.isEmpty(skuStockList))return;
        for(int i=0;i<skuStockList.size();i++){
            SkuStock skuStock = skuStockList.get(i);
            if(StringUtils.isEmpty(skuStock.getSkuCode())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    @Override
    public ProductResult getUpdateInfo(Long id) {
        return productDao.getUpdateInfo(id);
    }

    @Override
    public Product getItem(Long id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public int update(Long id, ProductParam productParam) {
        //更新商品信息
        Product product = productParam;
        product.setId(id);
        int count = productMapper.updateByPrimaryKeySelective(product);
        //会员价格
//        MemberPriceExample pmsMemberPriceExample = new MemberPriceExample();
//        pmsMemberPriceExample.createCriteria().andProductIdEqualTo(id);
//        memberPriceMapper.deleteByExample(pmsMemberPriceExample);
//        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);
//        //阶梯价格
//        ProductLadderExample ladderExample = new ProductLadderExample();
//        ladderExample.createCriteria().andProductIdEqualTo(id);
//        productLadderMapper.deleteByExample(ladderExample);
//        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id);
//        //满减价格
//        ProductFullReductionExample fullReductionExample = new ProductFullReductionExample();
//        fullReductionExample.createCriteria().andProductIdEqualTo(id);
//        productFullReductionMapper.deleteByExample(fullReductionExample);
//        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);
//        //修改sku库存信息
//        handleUpdateSkuStockList(id, productParam);
//        //修改商品参数,添加自定义商品规格
//        ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
//        productAttributeValueExample.createCriteria().andProductIdEqualTo(id);
//        productAttributeValueMapper.deleteByExample(productAttributeValueExample);
//        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id);
        return count;
    }

//    private void handleUpdateSkuStockList(Long id, ProductParam productParam) {
//        //当前的sku信息
//        List<SkuStock> currSkuList = productParam.getSkuStockList();
//        //当前没有sku直接删除
//        if(CollUtil.isEmpty(currSkuList)){
//            SkuStockExample skuStockExample = new SkuStockExample();
//            skuStockExample.createCriteria().andProductIdEqualTo(id);
//            skuStockMapper.deleteByExample(skuStockExample);
//            return;
//        }
//        //获取初始sku信息
//        SkuStockExample skuStockExample = new SkuStockExample();
//        skuStockExample.createCriteria().andProductIdEqualTo(id);
//        List<SkuStock> oriStuList = skuStockMapper.selectByExample(skuStockExample);
//        //获取新增sku信息
//        List<SkuStock> insertSkuList = currSkuList.stream().filter(item->item.getId()==null).collect(Collectors.toList());
//        //获取需要更新的sku信息
//        List<SkuStock> updateSkuList = currSkuList.stream().filter(item->item.getId()!=null).collect(Collectors.toList());
//        List<Long> updateSkuIds = updateSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
//        //获取需要删除的sku信息
//        List<SkuStock> removeSkuList = oriStuList.stream().filter(item-> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
//        handleSkuStockCode(insertSkuList,id);
//        handleSkuStockCode(updateSkuList,id);
//        //新增sku
//        if(CollUtil.isNotEmpty(insertSkuList)){
//            relateAndInsertList(skuStockDao, insertSkuList, id);
//        }
//        //删除sku
//        if(CollUtil.isNotEmpty(removeSkuList)){
//            List<Long> removeSkuIds = removeSkuList.stream().map(SkuStock::getId).collect(Collectors.toList());
//            SkuStockExample removeExample = new SkuStockExample();
//            removeExample.createCriteria().andIdIn(removeSkuIds);
//            skuStockMapper.deleteByExample(removeExample);
//        }
//        //修改sku
//        if(CollUtil.isNotEmpty(updateSkuList)){
//            for (SkuStock pmsSkuStock : updateSkuList) {
//                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
//            }
//        }
//
//    }

    @Override
    public List<Product> list(ProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andIsdeleteEqualTo(0);
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
//        if (productQueryParam.getVerifyStatus() != null) {
//            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
//        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andNameLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(productQueryParam.getProductSn())) {
            criteria.andCodeEqualTo(productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            criteria.andBrandIdEqualTo(productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            criteria.andProductCategoryIdEqualTo(productQueryParam.getProductCategoryId());
        }
        return productMapper.selectByExample(productExample);
    }

    @Override
    public int publish(Long id, Integer status) {
        Product product = getItem(id);
        product.setPublishStatus(status);
        int count = productMapper.updateByPrimaryKeySelective(product);
        return count;
    }

//    @Override
//    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
//        Product product = new Product();
////        product.setVerifyStatus(verifyStatus);
//        ProductExample example = new ProductExample();
//        example.createCriteria().andIdIn(ids);
////        List<ProductVertifyRecord> list = new ArrayList<>();
////        int count = productMapper.updateByExampleSelective(product, example);
////        //修改完审核状态后插入审核记录
////        for (Long id : ids) {
////            ProductVertifyRecord record = new ProductVertifyRecord();
////            record.setProductId(id);
////            record.setCreateTime(new Date());
////            record.setDetail(detail);
////            record.setStatus(verifyStatus);
////            record.setVertifyMan("test");
////            list.add(record);
////        }
////        productVertifyRecordDao.insertList(list);
//        return count;
//    }

    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        Product record = new Product();
        record.setPublishStatus(publishStatus);
        ProductExample example = new ProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int recommend(Long id, Integer status) {
        Product product = getItem(id);
        product.setRecommandStatus(status);
        int count = productMapper.updateByPrimaryKeySelective(product);
        return count;
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        Product record = new Product();
        record.setRecommandStatus(recommendStatus);
        ProductExample example = new ProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

//    @Override
//    public int updateNewStatus(List<Long> ids, Integer newStatus) {
//        Product record = new Product();
//        record.setNewStatus(newStatus);
//        ProductExample example = new ProductExample();
//        example.createCriteria().andIdIn(ids);
//        return productMapper.updateByExampleSelective(record, example);
//    }

    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        Product record = new Product();
        record.setIsdelete(deleteStatus);
        ProductExample example = new ProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int delete(Long id, Integer status) {
        Product product = getItem(id);
        product.setIsdelete(status);
        int count = productMapper.updateByPrimaryKeySelective(product);
        return count;
    }

    @Override
    public List<Product> list(String keyword) {
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andIsdeleteEqualTo(0);
        if(!StringUtils.isEmpty(keyword)){
            criteria.andNameLike("%" + keyword + "%");
            productExample.or().andIsdeleteEqualTo(0).andCodeLike("%" + keyword + "%");
        }
        return productMapper.selectByExample(productExample);
    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            log.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
